<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Leon</title>
</head>
<body>
  <form>
    名字：<input type="text" id="username"> <br>
    密码：<input type="text" id="pass"> <br>
    <button id="btn">提交</button>
  </form>
</body>
</html>
<script>
  // 点击按钮实现登录
  document.querySelector('#btn').onclick = function(){
    let username = document.querySelector('#username').value;
    let pass = document.querySelector('#pass').value;

    // ajax请求
    ajax('/login',`username=${username}&pass=${pass}`,'post').then(res=>{console.log(res);})
    return false;
  }

  function ajax(url,data=null,type='get'){
    return new Promise((resolve,reject)=>{
      let xhr = new XMLHttpRequest();
      // 判断请求方式
      if(type == 'post'){
        xhr.open(type,url)
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xhr.send(data);
      }else{
        xhr.open(type,`${url}?${data}`);
        xhr.send();
      }
      xhr.onreadystatechange = function(){
        if(xhr.status == 200){
          if(xhr.readyState == 4){
            resolve(JSON.parse(xhr.responseText));
          }
        }else{
          reject('请求失败');
        }
      }
    })
  }
</script>